<template>
  <div class="warp-container">
    <!-- 导航栏 编辑器-->
    <div v-if="queryParams && queryParams.design_type == 1" class="header-container">
      <Header />
    </div>
    <div v-else class="header-container">
      <Header />
    </div>
    <!-- 导航栏 -->

    <!-- 画布 -->
    <div id="canvasContentEl" class="canvas-content">
      <canvas ref="canvasContentEl1" id="canvas"></canvas>
      <div  v-if="queryParams && queryParams.design_type != 1" class="water-container"></div>
    </div>
    <!-- 画布 -->

    <!-- 尾部 -->
    <div v-if="queryParams && queryParams.design_type == 1" id="footer-container" class="footer-container">
      <Footer />
    </div>
    <!-- 用户尾部 -->

    <!-- 提示 -->
    <div
      v-else
      id="footer-container"
      class="footer-container"
      :class="{
        'design-footer-container': queryParams && queryParams.design_type == 2
      }">
      <!-- 通知栏 -->
      <div class="noticebar">
        <div class="noticebar-text">
          <span class="color-red">温馨提示：&#8593 &#8593</span>
          <span class="color-gary">内容可</span>
          <span class="color-blue">移动</span>
          <span class="color-gary">(按住拖动)、</span>
          <span class="color-blue">缩放</span>
          <span class="color-gary">(按住</span>
          <img class="image-icon" src="https://img.alicdn.com/imgextra/i1/1888948409/O1CN01SLRwMV2BzNOm6ulMZ_!!1888948409.png">
          <span class="color-gary">可缩放)、</span>
          <span class="color-blue">旋转</span>
          <span class="color-gary">(按住</span>
          <img class="image-icon" src="https://dutuku.img.isvg.cn/2023/09/30/20230930183336-rotate.png">
          <span class="color-gary">可旋转)、</span>
          <span class="color-gary">可缩放)、</span>
          <span class="color-blue">镜像</span>
          <span class="color-gary">(按住</span>
          <img class="image-icon" src="https://dutuku.img.isvg.cn/2023/09/30/20230930183423-jingxiang.png">
          <span class="color-gary">可镜像)、</span>
          <span class="color-gary">可改字、可换图，保存后高清无水印。</span>
        </div>
      </div>
      <!-- 元素列表 -->
      <div class="footer-layer-container">
        <div class="layer-content">
          <template
            v-for="(item, index) in itemList">
            <div
              v-if="item.selectable"
              class="layer-item"
              :class="{
                'layer-item-active': currentSelectionElement && index === currentSelectionElement._index
              }"
              @click="handleObjectItem(index)">
              <!-- 图片 -->
              <div v-if="item.type === 'image'" class="img-item">
                <van-image
                  width="100%"
                  height="100%"
                  fit="contain"
                  :src="item.src"
                />
                <div v-if="currentSelectionElement && index === currentSelectionElement._index" class="change-image-tip">
                  <van-icon name="photo-o" size="20" />
                  <div class="change-image-text">点击替换</div>
                </div>
              </div>
              <div v-else class="textbox-item">
                <span class="text">{{ item.text }}</span>
                <div v-if="currentSelectionElement && index === currentSelectionElement._index" class="change-image-tip">
                  <van-icon name="edit" size="20" />
                  <div class="change-image-text">编辑文字</div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <!-- 隐藏点击上传图片元素 -->
    <van-uploader
      v-if="queryParams && (queryParams.origin === 'h5' || queryParams.origin === 'kuaishou' || queryParams.origin === 'weixin')"
      id="h5Upload"
      name="file"
      style="display: none;"
      :preview-image="false"
      :after-read="h5UploadImage">
    </van-uploader>

    <!-- 更换文字 -->
    <van-popup
      v-model="showPopup"
      @close="handleEditTextClose"
      position="center"
      class="edit-text-container"
      :overlay-style="{
        background: 'rgba(0, 0, 0, .8)'
      }">
      <div class="edit-text-content">
        <div class="title-content">修改内容</div>
        <van-field
          v-model="text"
          label=""
          size="large"
          label-width="0"
          placeholder="请输入您要替换的文字"
          class="text-field"
          :clearable="true" />
      </div>
      <div class="btn-container">
        <van-button type="default" block style="margin-right: 12px;" @click="handleEditTextClose">关闭</van-button>
        <van-button type="info" block @click="handleConfirmText" color="linear-gradient(to right, #8773f9, #8CA6DB)">确定</van-button>
      </div>
    </van-popup>

    <!-- 添加底图 -->
    <van-popup
      v-model="showaddImageBackground"
      round
      :style="{ maxHeight: '80%', width: '250px'}"
      :close-on-click-overlay="false">
      <div class="image-container artworks-container">
        <van-uploader
          name="file"
          :preview-image="false"
          :max-size="3145728" @oversize="onOversize"
          :after-read="h5UploadBackgroundImage">
          <van-image
            width="100%"
            height="250px"
            fit="contain"
            src="https://qiniu-res.jintianwang.cc/20221212165919-d1deaa66c29f585ba8e1cdad4eebf29a.png"
            style="float: left;"
          />
        </van-uploader>
      </div>
    </van-popup>
  </div>
</template>

<script>
  import Header from '../components/Header';
  import Footer from '../components/Footer';
  import { diyTemplateDetailById, getAuthToke, checkTxt, artworksDetailById } from '@/utils/api';
  export default {
    name: 'Me',
    components: {
      Footer,
      Header
    },
    data() {
      return {
        showSelectBackground: false,
        canvas: null,
        queryParams: null,
        showPopup: false,
        text: '',
        currentIndex: 0,
        itemList: [],
        currentSelectionElement: null,
        showaddImageBackground: false
      }
    },

    watch: {
      '$store.state.user.queryParams': {
        immediate: true,
        handler(val, oldVal) {
          this.queryParams = val;
        }
      },
      '$store.state.design.showTextFlag': {
        immediate: true,
        handler(val, oldVal) {

          if (val) {
            const handAccountCanvas = this.handAccountCanvas.getObject().getActiveObject();
            this.text = handAccountCanvas.text;
          }

          this.showPopup = val;
        }
      },
      '$store.state.design.currentSelectionElement': {
        immediate: true,
        handler(val, oldVal) {
          if (val) {
            this.currentSelectionElement = val;
          } else {
            this.currentSelectionElement = null;
          }
        } 
      },
      '$store.state.design.itemList': {
        immediate: true,
        deep: true,
        handler(val, oldVal) {
          if (val) {
            this.itemList = val;
          }
        } 
      },
      '$store.state.design.showAddBackgroundImage': {
        immediate: true,
        deep: true,
        handler(val) {
          if (val) {
            this.showaddImageBackground = false;
          }
        }
      }
    },

    mounted() {
      this.$nextTick(async () => {
        let queryParams = this.$store.state.user.queryParams;
        if (queryParams.author_id) {
          this.showaddImageBackground = true;
        }
        this.getAuthToke();
        await this.handAccountCanvas.initCanvas(queryParams.design_type);
        this.getDiyTemplateDetailById();
      })
    },
    methods: {
      onOversize(){
        this.$toast({
          position: "center",
          message: "图片大小不能超过3M",
          duration: 3 * 1000,
        });
      },
      // h5上传底图图片
      h5UploadBackgroundImage(files) {
        this.handAccountCanvas.h5Upload(files).then(result => {
          let image = result.cover_path;
          this.handAccountCanvas.setCanvasBackground({
            type: 'img',
            uri: image,
          }).then(() => {
            this.showaddImageBackground = false;
          });
        });
      },

      // 设置
      handleObjectItem(_index) {
        const handAccountCanvas = this.handAccountCanvas.getObject();
        const items = handAccountCanvas.getObjects();
        let actvieItem = items[_index];
        handAccountCanvas.setActiveObject(actvieItem);
        handAccountCanvas.renderAll();
        if (actvieItem.type === 'textbox') {
          this.$store.dispatch('design/setShowTetxFlag', true);
        } else if (actvieItem.type === 'image') {
          this.handAccountCanvas.handleChangeImage();
        }
      },
      
      // 确定输入文字
      handleConfirmText() {
        this.$toast.loading({
          message: '检测中...',
          position: 'center',
          forbidClick: true,
          duration: 0
        });
        checkTxt({
          text: this.text,
        }).then(result => {
          this.$toast.clear();
          if (result && result.data) {
            this.handAccountCanvas.updateTextBox({
              type: 'text',
              content: this.text
            });
            this.handleEditTextClose();
            this.itemList[this.currentSelectionElement._index].text = this.text;
          }
        }).catch((err) => {
          this.$toast.clear();
          this.$toast({
            message: err.msg,
            duration: 1500,
            forbidClick: true
          });
        })
      },

      // 关闭文字框
      handleEditTextClose() {
        this.$store.dispatch('design/setShowTetxFlag', false);
      },

      // 上传图片
      h5UploadImage(files) {
        this.handAccountCanvas.h5Upload(files).then(result => {
        let image = result.cover_path;
        // 检测图片
        this.handAccountCanvas.censorImage(image).then(result_ => {
          this.handAccountCanvas.updatedImageItem({
            type: 'src',
            uri: result_.url
          }).then(imageResult => {
            this.itemList[this.currentSelectionElement._index].src = result_.url;
            if (imageResult && imageResult.width > 200) {
              this.handAccountCanvas.updatedImageItem({
                type: 'width'
              })
            }
          })
        })
      });
      },

      // 获取详情
      getDiyTemplateDetailById() {
        let queryParams = this.$store.state.user.queryParams;
        let currentTime = parseInt(new Date().getTime() / 1000);
        let requestTime = parseInt(((queryParams.t || 0) / 1000));
        if (queryParams.t && (currentTime - requestTime) > 90 && queryParams.origin !== 'h5') {
          location.href = 'https://design.guxitk.com';
          return;
        }
        if (queryParams.id) {
          this.$toast.loading({
            message: '加载中',
            position: 'center',
            forbidClick: true,
            duration: 0
          });
          artworksDetailById({
            id: queryParams.id
          }).then(result => {
            this.$toast.clear();
            if (result && result.data && result.data.length > 0) {
              let data = result.data[0];
              this.$store.dispatch('design/setTemplateDetail', data);
              let params = data.font_attribute;
              params.objects.forEach((item, index) => {
                item._index = index;
              });
              this.$store.dispatch('design/setItemList', params.objects);
              this.handAccountCanvas.canvasLoadJson(params, queryParams.design_type).then(() => {
                this.handAccountCanvas.setFirstItemActive();
              });
            }
          }).catch(() => {
            this.$toast.clear();
          })
        }
      },

      // 获取token
      getAuthToke() {
        let queryParams = this.$store.state.user.queryParams;
        let currentTime = parseInt(new Date().getTime() / 1000);
        let requestTime = parseInt(((queryParams.t || 0) / 1000));
        console.log(333322)
        if (queryParams.t && (currentTime - requestTime) > 90 && queryParams.origin !== 'h5') {
          tt.miniProgram.reLaunch({
            url: `/subPagesA/diyAvatar/moreAvatar?tid=${queryParams.tool_id || ''}&sc=${queryParams.seach_code || ''}`,
            success(res) {
              console.log("跳转成功", res);
            },
            fail(err) {
              console.log("navigateTo调用失败", err);
            },
          });
        }
        if (queryParams && queryParams.auth_key) {
          getAuthToke({
            auth_key: queryParams.auth_key
          }).then(result => {
            if (result && result.data && result.data.token) {
              this.$store.dispatch('user/setToken', result.data.token);
            }
          })
        }
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
  @import '../../assets/common.less';

  .warp-container{
    height: 100%;
    background-color: @accessoryColor;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
  }

  .canvas-container{
    // border-radius: 8px;
    overflow-x: hidden;
    -webkit-transform: rotate(0deg);
    position: absolute !important;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
  }

  .canvas-content{
    width: 100%;
    // border-radius: 8px;
    // overflow: hidden;
    overflow-y: auto;
    overflow-x: hidden;
    flex: 1;
    -webkit-transform: rotate(0deg);
    position: relative;
    background-size: cover;

    .water-container{
      width: 100%;
      height: 100%;
      // background: url(https://img.alicdn.com/imgextra/i4/1888948409/O1CN01teMfIu2BzNOvSPmhT_!!1888948409.png);
      background: url(https://baiwan-product.oss-cn-hangzhou.aliyuncs.com/watermark/desingshuiying.png);
      background-size: cover;
      position: absolute;
      pointer-events: none;
    }
  }

  .header-container{
    height: 46px;
    width: 100%;
    background: @accessoryColor;
    // position: fixed;
    // top: 0;
    // z-index: 999;
  }

  .header-container-padding{
    padding-top: 12px;
  }

  .footer-container{
    height: 68px;
    width: 100%;
    background: @mainColor;
    position: relative;
    z-index: 9999;
  }

  .design-footer-container{
    height: 120px;
    z-index: 99;

    .noticebar {
      overflow: hidden;
      white-space: nowrap;
      background-color: #444;
      padding: 6px 0;
      display: flex;
      align-items: center;
      vertical-align: center;
      margin-bottom: 8px;
    }

    .color-red{
      color: rgb(235, 32, 32);
      font-size: 12px;
    }

    .color-gary{
      color: #f5f5f5;
      font-size: 12px;
    }

    .color-blue{
      color: #8773f9;
      font-size: 12px;
    }

    .image-icon{
      width: 16px;
      height: 16px;
      position: relative;
      top: 4px;
    }

    .noticebar-text {
      display: inline-block;
      padding-left: 100%;
      animation: noticebar-slide 24s linear infinite;
    }
  }

  .footer-layer-container{
    width: 100%;
    
    .layer-content{
      width: 100%;
      padding: 0 12px;
      display: flex;
      align-items: center;
      overflow-y: auto;

      .layer-item{
        max-width: 60px;
        min-width: 60px;
        height: 60px;
        margin-right: 5px;
        border-radius: 4px;
        background-image: linear-gradient(90deg, rgba(0, 0, 0, .8), rgba(0, 0, 0, .8)), linear-gradient(90deg, #d2d2d2, #d2d2d2);
        border: 2px solid transparent;
        overflow: hidden;
      }

      .layer-item,
      .larer-item-active {
        background-clip: padding-box, border-box;
        background-origin: padding-box, border-box;
      }

      .layer-item-active{
        border: 2px solid transparent;
        border-radius: 4px;
        background-image: linear-gradient(90deg, rgba(0, 0, 0, .8), rgba(0, 0, 0, .8)), linear-gradient(180deg, #B993D6, #8CA6DB);
      }

      .textbox-item,
      .img-item{
        width: 100%;
        height: 100%;
        position: relative;
      }

      .change-image-tip{
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        background: rgba(0, 0, 0, .8);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #8773f9;
        flex-direction: column;
      }

      .change-image-text{
        font-size: 12px;
        font-weight: bold;
      }

      .textbox-item{
        width: 100%;
        height: 100%;
        padding: 2px;
        display: flex;
        align-items: center;
        justify-content: center;

        .text{
          font-size: 12px;
          color: #fff;
        }
      }
    }
  }

  .edit-text-container{
    width: 288px;
    padding: 12px 16px 24px 16px;
    border-radius: 8px;
    overflow: hidden;
    top: 25%;

    .title-content{
      font-size: 16px;
      font-weight: bold;
      text-align: center;
      padding: 12px 0 24px 0;
    }

    .text-field{
      background-color: #f5f5f5;
      border-radius: 8px;
      margin-bottom: 24px;
    }

    .btn-container{
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  @keyframes noticebar-slide {
    0% {
      transform: translateX(0);
    }
    100% {
      transform: translateX(-100%);
    }
  }
</style>
